package com.hmjk.health.home;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.NetService;
import com.hmjk.health.util.OnFragmentEventCallback;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class RetrievePswFragment extends Fragment implements OnClickListener{
	private final String TAG = RetrievePswFragment.class.getSimpleName(); 
	private HealthApp mApp = null;
	private OnFragmentEventCallback mCallback;
	private EditText mPhone;
	private Button mGet;
	private boolean attached = false;
	
	private void logd(String info){
		//Log.d(TAG,info);
	}

	@Override
	public void onAttach(Activity activity){
		super.onAttach(activity);
		mApp = (HealthApp)activity.getApplication();
		try{
			mCallback = (OnFragmentEventCallback)activity;
		}catch(ClassCastException e){
			throw new ClassCastException(activity.getClass().getName() + " must implement OnFragmentEventCallback");
		}
		attached = true;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
		View v = inflater.inflate(R.layout.retrieve_fragment, container, false);
		
		ImageButton back = (ImageButton)v.findViewById(R.id.back);
		back.setOnClickListener(this);
		
		mPhone = (EditText)v.findViewById(R.id.phonenum);
		mGet = (Button)v.findViewById(R.id.getpwd);
		mGet.setOnClickListener(this);
		attached = true;
		return v;
	}

	@Override
	public void onDetach(){
		attached = false;
		super.onDetach();
		logd("onDetach");
	}
	
	@Override
	public void onDestroyView(){
		attached = false;
		mHandler.removeMessages(MSG_RETRIEVE_COUNTDOWN);
		super.onDestroyView();
		logd("onDestroyView");
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			mCallback.onEvent(SignInActivity.ACT_BACK_TO_SIGNIN, null);
		}
		break;
		case R.id.getpwd:{
			String p = mPhone.getText().toString().trim();
			if((p == null) || (p.length() < 11)){
				Toast.makeText(getActivity(), R.string.invalid_phonenum, Toast.LENGTH_LONG).show();
				break;
			}
			
			Intent si = new Intent(getActivity(), NetService.class);
			si.setAction(NetService.RETRIEVE_PASSWORD);
			si.putExtra("phone", p);
			Time t = new Time();
			t.setToNow();
			String stamp = "RETRIEVE_PASSWORD" + t.toString(); 
			si.putExtra("stamp",stamp);
			mApp.addNetHandler(stamp,mHandler);
			getActivity().startService(si);
			
			mPhone.setEnabled(false);
			mGet.setEnabled(false);
			mGet.setText(R.string.idcode_getting);
		}
		break;
		}
		
	}
	
	private static final int MSG_RETRIEVE_COUNTDOWN = 303;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			if(!attached)
				return;
			
			switch(msg.what){
			case MSG_RETRIEVE_COUNTDOWN:{
				Bundle b = msg.getData();
				int count = b.getInt("count");
				count--;
				if(count >= 0){
					String h = getResources().getString(R.string.retrieve_but_txt_wait,count);
					mGet.setText(h);
					mGet.setEnabled(false);
					Message mm = mHandler.obtainMessage(MSG_RETRIEVE_COUNTDOWN);
					
					b.putInt("count", count);
					mm.setData(b);
					mHandler.sendMessageDelayed(mm, 1000);
				}else{
					mGet.setText(R.string.getcode);
					mGet.setEnabled(true);
				}
			}
			break;
			case HealthApp.MSG_NET_RESPONSE:{
				Bundle b = msg.getData();
				String stamp = b.getString("stamp","ooh!No!");
				boolean canceled = b.getBoolean("canceled", false);
				if(stamp.startsWith("RETRIEVE_PASSWORD")){
					String sjson = b.getString("json");
					if(sjson != null){
						try {
							JSONObject json = new JSONObject(sjson);
							int code = json.getInt("code");
							if(code == 200){
								String state = json.getString("state");
								mPhone.setEnabled(true);
								if(state.equals("00")){
									String num = mPhone.getText().toString().trim();
									String h = getResources().getString(R.string.retrieve_but_txt_wait,60);
									mGet.setText(h);
									mGet.setEnabled(false);
									String disNum = mApp.numberToHidenString(num);
									String show = getResources().getString(R.string.retrieve_ok_msg,disNum);
									Toast.makeText(getActivity(), show, Toast.LENGTH_LONG).show();	
									
									Message mm = mHandler.obtainMessage(MSG_RETRIEVE_COUNTDOWN);
									Bundle b1 = new Bundle();
									b1.putInt("count", 60);
									mm.setData(b1);
									mHandler.sendMessageDelayed(mm, 1000);
									break;
								}else if(state.equals("01")){
									Toast.makeText(getActivity(),R.string.server_noResp, Toast.LENGTH_LONG).show();	
									mGet.setText(R.string.retrieve_but_txt);
									mGet.setEnabled(true);
									break;
								}else if(state.equalsIgnoreCase("1E")){
									Toast.makeText(getActivity(),R.string.mobile_noRegistered, Toast.LENGTH_LONG).show();	
									mGet.setText(R.string.retrieve_but_txt);
									mGet.setEnabled(true);
									break;
								}else if(state.equalsIgnoreCase("03")){
									//never be here
									break;
								}
							}
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} 
					}
					mPhone.setEnabled(true);
					Toast.makeText(getActivity(),R.string.req_failed, Toast.LENGTH_LONG).show();
					mGet.setText(R.string.getcode);
					mGet.setEnabled(true);
				}
			}
			break;
			}
		}
	};
}
